import { createRouter, createWebHistory } from 'vue-router'
import BookList from '../components/BookList.vue'
import AddBook from '../components/AddBook.vue'
import Login from '../components/Login.vue'
import AuthorList from '../components/AuthorList.vue'
import TagList from '../components/TagList.vue'
import BookDetail from '../components/BookDetail.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/books'
    },
    {
      path: '/books',
      component: BookList
    },
    {
      path: '/add-book',
      component: AddBook
    },
    {
      path: '/authors',
      component: AuthorList
    },
    {
      path: '/tags',
      name: 'tags',
      component: TagList
    },
    {
      path: '/book/:id',
      name: 'book-detail',
      component: BookDetail
    },
    {
      path: '/login',
      component: Login
    }
  ]
})

// 全局导航守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path === '/login') {
    next()
  } else if (!token) {
    next('/login')
  } else {
    next()
  }
})

export default router